using System.Collections.ObjectModel;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class PhysicsCheck : MonoBehaviour {

    private Rigidbody2D rb;
    private CapsuleCollider2D colli;
    private PlayerController playerController;

    [Header("检测参数")]
    public bool manual;             // 物理检测范围是手动给出还是自动计算
    public bool isPlayer;           // 当前挂载对象是否是Player
    public Vector2 bottomOffset;
    public Vector2 leftOffset;
    public Vector2 rightOffset;
    public float checkRadius;       // 人物的检测半径
    public LayerMask groundLayer;   // 地面LayerMask

    [Header("状态")]
    public bool isGround;           // 角色当前是否触地
    public bool touchLeftWall;      // 触碰左墙
    public bool touchRightWall;     // 触碰右墙壁
    public bool isWall;             // 是否滑墙
    
    private void Awake() {
        colli = GetComponent<CapsuleCollider2D>();
        rb = GetComponent<Rigidbody2D>();
        isWall = false;

        if (isPlayer) {
            playerController = GetComponent<PlayerController>();
        }

        if (!manual) {
            rightOffset = new Vector2((colli.bounds.size.x + colli.offset.x) / 2, colli.bounds.size.y / 2);
            leftOffset = new Vector2(-rightOffset.x, rightOffset.y);
        }
    }

    void Update() {
        Check();
    }

    void Check() {
        // 地面判断
        if (isWall) {
            isGround = Physics2D.OverlapCircle((Vector2)transform.position + new Vector2(bottomOffset.x * transform.localScale.x, bottomOffset.y), checkRadius, groundLayer);
        } else {
            isGround = Physics2D.OverlapCircle((Vector2)transform.position + new Vector2(bottomOffset.x * transform.localScale.x, 0f), checkRadius, groundLayer);
        }

        // 墙体判断
        touchLeftWall = Physics2D.OverlapCircle((Vector2)transform.position + leftOffset, checkRadius, groundLayer);
        touchRightWall = Physics2D.OverlapCircle((Vector2)transform.position + rightOffset, checkRadius, groundLayer);

        if (isPlayer) {
            isWall = rb.velocity.y < 0f && ((touchLeftWall && playerController.inputDirection.x < 0f) || (touchRightWall && playerController.inputDirection.x > 0f));
        }
    }
    
    private void OnDrawGizmosSelected() {
        // 测试：绘制出检测区域
        if (isWall) {
            Gizmos.DrawWireSphere((Vector2)transform.position + new Vector2(bottomOffset.x * transform.localScale.x, bottomOffset.y), checkRadius);
        } else {
            Gizmos.DrawWireSphere((Vector2)transform.position + new Vector2(bottomOffset.x * transform.localScale.x, 0f), checkRadius);
        }
        Gizmos.DrawWireSphere((Vector2)transform.position + leftOffset, checkRadius);
        Gizmos.DrawWireSphere((Vector2)transform.position + rightOffset, checkRadius);
    }

}
